﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SubFps
{
    public class SrtFixer
    {
        private double FpsChangeRate;
        private SrtFixArgs Args;
        public SrtFixer(SrtFixArgs args)
        {
            if (args == null)
                throw new ArgumentNullException("Args");
            Args = args;
            FpsChangeRate = args.CurrentFPS / args.OutFPS;
        }
        public void FixSrt()
        {
            AssertFileExists(Args.FileName);
            var contentStr = ReadFile(Args.FileName);
            var content = contentStr.ToCharArray();
            var timeStartIndex = 0;
            while ((timeStartIndex = IndexOfNextTime(contentStr, timeStartIndex)) >= 0)
            {
                ReplaceTime(content, timeStartIndex);
                timeStartIndex = contentStr.IndexOf(':', timeStartIndex + 14) - 2;
                ReplaceTime(content, timeStartIndex);
                timeStartIndex += 12;
            }
            WriteFile(Args.FileName, content);
        }
        private static void WriteFile(string fileName, char[] content)
        {
            File.Move(fileName, fileName + "_old.srt");
            using (var outfile = new StreamWriter(fileName, false, Encoding.UTF8))
            {
                outfile.Write(content);
                outfile.Close();
            }
        }
        private static string ReadFile(string fileName)
        {
            string contentStr;
            using (var file = new StreamReader(fileName, Encoding.UTF8))
            {
                contentStr = file.ReadToEnd();
                file.Close();
            }
            return contentStr;
        }
        private int IndexOfNextTime(string input, int startIndex)//returns index of next time in array or -1 if reaches end of array
        {
            var arrowIndex = input.IndexOf("-->", startIndex);
            if (arrowIndex < 0)
                return arrowIndex;
            var col1Index = input.LastIndexOf(':', arrowIndex);
            return col1Index < 0 ? col1Index : col1Index - 5;
        }
        private void ReplaceTime(char[] input, int index)
        {
            input[index + 8] = '.';
            var timeStr = new string(input, index, 12);
            TimeSpan time = TimeSpan.Parse(timeStr);
            TimeSpan newTime = TimeSpan.FromMilliseconds((long)(time.TotalMilliseconds * FpsChangeRate) + Args.Delay);
            DateTime dt = new DateTime(2000, 1, 1, newTime.Hours, newTime.Minutes, newTime.Seconds, newTime.Milliseconds);
            Array.Copy(dt.ToString("HH:mm:ss,fff").ToCharArray(), 0, input, index, 12);
        }
        public static void RevertFromFileName(string fileName)
        {
            string oldFileName;
            AssertFileExists(fileName);
            AssertFileExists(oldFileName = fileName + "_old.srt");

            File.Delete(fileName);
            File.Move(oldFileName, fileName);
        }
        private static void AssertFileExists(string fileName)
        {
            if (!File.Exists(fileName))
                throw new FileNotFoundException("File Not found : " + fileName);
        }
    }
}
